package com.zym.init.core.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.zym.init.core.constant.CommonConstant;
import com.zym.init.core.constant.RedisConstant;
import com.zym.init.model.bo.LoginUser;
import com.zym.init.core.utils.AddressUtils;
import com.zym.init.core.utils.IpUtils;
import com.zym.init.core.utils.RedisUtils;
import com.zym.init.core.utils.ServletUtils;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

import static com.zym.init.core.constant.CommonConstant.TOKEN_PREFIX;

/**
 * Token 服务
 */
@Slf4j
@Component
public class TokenService {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    /**
     * 密钥
     */
    @Value("${token.secret-key}")
    private String secretKey;

    /**
     * 有效期(小时)
     */
    @Value("${token.validity-hour}")
    private int validityHour;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        String token = getToken();
        if (StringUtils.hasLength(token)) {
            try {
                JWT claims = JWTUtil.parseToken(token);
                String uuid = claims.getPayloads().getStr(CommonConstant.LOGIN_USER_KEY);
                String tokenCacheKey = getTokenCacheKey(uuid);
                return (LoginUser) RedisUtils.get(tokenCacheKey);
            } catch (Exception e) {
                log.error("获取用户信息异常：{}", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 创建token
     *
     * @param loginUser 用户信息
     * @return token
     */
    public String createToken(LoginUser loginUser) {
        String token = UUID.fastUUID().toString();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(CommonConstant.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 刷新token有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        // 更新用户登录时间
        loginUser.setLoginTime(DateUtil.now());
        // 更新token过期时间
        loginUser.setExpireTime(DateUtil.formatDateTime(DateUtil.offsetHour(DateUtil.parseDate(loginUser.getLoginTime()), validityHour)));
        // 根据uuid将loginUser缓存
        String userKey = getTokenCacheKey(loginUser.getToken());
        // 设置缓存
        RedisUtils.set(userKey, loginUser, (long) validityHour * 60 * 60);
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (BeanUtil.isNotEmpty(loginUser) && StringUtils.hasLength(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.hasLength(token))
        {
            String userKey = getTokenCacheKey(token);
            RedisUtils.del(userKey);
        }
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成token
     *
     * @param claims 数据声明
     * @return token
     */
    private String createToken(Map<String, Object> claims) {
        return JWTUtil.createToken(claims, secretKey.getBytes());
    }

    /**
     * 获取token
     *
     * @return token
     */
    public String getToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return "";
        }
        return resolveToken(attributes.getRequest());
    }

    /**
     * 解析token
     *
     * @param req 请求
     * @return token
     */
    public String resolveToken(HttpServletRequest req) {
        String bearerToken = req.getHeader(header);
        if (bearerToken != null && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 获取token缓存键
     *
     * @param uuid uuid
     * @return 缓存键
     */
    private String getTokenCacheKey(String uuid) {
        return RedisConstant.JWT_TOKEN_KEY + uuid;
    }
}
